class Solution {
public:

    struct Compare
    {
        bool operator()(const pair<string, int>& x, const pair<string, int>& y)
        {
            return x.second > y.second;
        }
    };

    vector<string> topKFrequent(vector<string>& words, int k) {
        map<string, int> countmap;
        for (auto& e : words)
        {
            countmap[e]++;
        }

        vector<pair<string, int>> v(countmap.begin(), countmap.end());

        stable_sort(v.begin(), v.end(), Compare());

        vector<string> strv;
        for (int i = 0; i < k; i++)
        {
            strv.push_back(v[i].first);
        }
        return strv;
    }
};